<template>
  <!-- 图表绘制区域 -->
  <div class="card_table event_echart">
    <!-- 工具栏 时间对比组 -->
    <div class="config_arr btwn">
      <div class="left">
        <!-- 时间跨度 -->
        <el-select
          class="min_el"
          @change="unitChange"
          :size="size"
          v-model="unit"
          placeholder="请选择"
        >
          <el-option
            v-for="item in unitArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>

        <!-- 时间查询区间 -->
        <el-date-picker
          class="time"
          :size="size"
          @change="dateSChange"
          v-model="dateS"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
        <timeRestrict :timeRestrict="{
          function: 'absolute_time',
          params: ['2021-01-01', '2021-01-02']
        }"></timeRestrict>
        <!-- <timeRestrict :timeRestrict="{
          function: 'dynamic_time',
          params: ['last_20_day', 'last_15_day']
        }"></timeRestrict> -->
        <!-- <template v-if="dateD&&dateD.length>0">
          vs
          <el-date-picker
            @change="dateDChange"
            :size="size"
            v-model="dateD"
            class="time"
             @change=""
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </template>
        <span v-else class="total_screen">
          <label>
            <i class="el-icon-plus"></i>
            对比时间
            <el-select @change="timeContrast" class="show_hidden" placeholder="请选择">
              <el-option label="上一段时间" value="1"></el-option>
              <el-option label="自定义" value="2"></el-option>
            </el-select>
          </label>
        </span>-->
      </div>
      <div class="right">
        <el-tooltip class="item" effect="dark" content="线状图" placement="top">
          <span
            @click="loadingQuery?null:echartType='line'"
            :class="echartType=='line'?'active':''"
          >
            <i class="el-icon-data-line"></i>
          </span>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="柱状图" placement="top">
          <span @click="loadingQuery?null:echartType='bar'" :class="echartType=='bar'?'active':''">
            <i class="el-icon-s-data"></i>
          </span>
        </el-tooltip>
        <!-- 无分组时，不支持饼状图 -->
        <el-tooltip
          v-if="byFields.length>0"
          class="item"
          effect="dark"
          content="饼状图"
          placement="top"
        >
          <span @click="loadingQuery?null:echartType='pie'" :class="echartType=='pie'?'active':''">
            <i class="el-icon-pie-chart"></i>
          </span>
        </el-tooltip>

        <el-tooltip v-else class="item" effect="dark" content="无分组时不支持饼状图" placement="top">
          <span>
            <i class="el-icon-pie-chart"></i>
          </span>
        </el-tooltip>
      </div>
    </div>
    <!-- 指标循环 -->
    <div v-if="messures.length>0" class="config_arr">
      <!-- class="cancle_arr index_arr" -->
      <span
        :class="messuresShow(_i)"
        @click="messuresCopyChange(_i)"
        v-for="(_i,_in) in messures"
        :key="_i.echartId + _i.name"
      >
        <span class="icon no_copy">{{convert(_in+1)}}</span>
        <span>{{_i.name}}</span>
      </span>
    </div>
    <!-- 分组循环 -->
    <div class="config_arr btwn no_line" v-if="byFields.length>0">
      <div class="left">
        <span class="group_sun" v-for="(_i,_in) in byFields" :key="_i.value">
          <groupChoose
            v-if="_i.options.length>0"
            @change="groupChange($event,_in)"
            :name="_i.propertyName"
            :optionsArr="_i.options"
            :checkedArr="_i.checked"
          ></groupChoose>
          <!-- <label>
            <i class="el-icon-setting"></i>
            {{_i.propertyName}}
            <span
              v-if="_i.checked.length>0"
              class="checklength"
            >{{_i.checked.length}}</span>
            <el-select
              @change="newChooseArr"
              class="show_hidden"
              v-model="_i.checked"
              multiple
              placeholder="请选择"
            >
              <el-option v-for="item in _i.options" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </label>-->
        </span>
      </div>

      <div class="right">
        <el-select :placeholder="rowLength()" v-model="loop" clearable :size="size">
          <el-option label="前五项" :value="5"></el-option>
          <el-option label="前十项" :value="10"></el-option>
          <el-option label="前十五项" :value="15"></el-option>
          <el-option label="前二十项" :value="20"></el-option>
          <el-option label="前二十五项" :value="25"></el-option>
          <el-option label="前三十项" :value="30"></el-option>
          <el-option label="前五十项" :value="50"></el-option>
        </el-select>
        <el-input v-model="searchChoose" clearable class="sel_inp" placeholder="查询关键字">
          <el-button
            @clear="newChooseArr"
            @click="newChooseArr"
            slot="append"
            icon="el-icon-search"
          ></el-button>
        </el-input>
      </div>
    </div>
    <!-- echarts 图标显示区域 -->
    <div class="ech_show">
      <!-- 折线图 柱状图 画板 -->
      <div
        v-loading="loadingQuery"
        element-loading-text="数据重载中。。。"
        element-loading-spinner="el-icon-loading"
        v-show="echartType=='line'||echartType=='bar'"
        id="echCanvas"
      ></div>
      <!-- 饼状图画板 -->
      <div
        v-loading="loadingQuery"
        element-loading-text="数据重载中。。。"
        element-loading-spinner="el-icon-loading"
        v-show="echartType=='pie'"
        :key="pieBool"
        class="pieCanvas"
      >
        <!-- 判断是否有对比时间，有对比时间用大看板，无对比时间用小看板 -->
        <template v-if="dataInit.length==2">
          <div class="pieContBig" v-for="_i in messuresCopy" :key="_i.id">
            <div class="head">{{_i.name}}</div>
            <div class="canvas" :id="_i.id+'pie'"></div>
          </div>
        </template>
        <template v-if="dataInit.length==1">
          <div class="pieContSmall" v-for="_i in messuresCopy" :key="_i.id">
            <div class="head">{{_i.name}}</div>
            <div class="canvas" :id="_i.id+'pie'"></div>
          </div>
        </template>
      </div>
      <div  v-if="byFields.length>0" class="echChoose">
        <div class="choose">
          <el-checkbox @change="allChoose" v-model="chooseChecked">全选</el-checkbox>
        </div>
        <!-- 折线图才会分指标点选 -->
        <div class="scrool" v-if="echartType=='line'">
          <div class="boxfather" v-for="(item,index) in rightChooseArrShow" :key="item.id">
            <div @click="showBoolChange(item.showBool,index)" class="head">
              <i v-if="item.showBool" class="el-icon-caret-bottom"></i>
              <i v-else class="el-icon-caret-right"></i>
              {{item.name}}
            </div>
            <div class="cont" v-if="rightChooseArrShow[index].showBool">
              <el-tooltip
                v-for="(_i) in item.childrenChoose"
                :key="_i"
                class="item"
                effect="dark"
                :content="_i"
                placement="left"
              >
                <div
                  @click="rightChooseArrInitChange(_i,index,false)"
                  :class="opacityShow(_i,index)?'line active':'line'"
                >{{_i}}</div>
              </el-tooltip>
            </div>
          </div>
        </div>
        <!-- 柱状图 饼图  点选统一化 -->
        <div class="scrool" v-if="echartType=='bar'||echartType=='pie'">
          <div class="boxfather">
            <div class="cont" v-if="rightChooseArrShow.length>0">
              <el-tooltip
                v-for="(_i) in rightChooseArrShow[0].childrenChoose"
                :key="_i"
                class="item"
                effect="dark"
                :content="_i"
                placement="left"
              >
                <div
                  :class="opacityShow(_i,0)?'line active':'line'"
                  @click="rightChooseArrInitChange(_i,0,true)"
                >{{_i}}</div>
              </el-tooltip>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>
<script>
import ElementResize from "@/utils/ElementResize.js";
import groupChoose from "./groupChoose.vue"; // 引入分组筛选选择组件
import { setTimeout } from "timers";
export default {
  name: "echartSelf",
  props: {
    queryTotal: {
      type: Object,
      default: () => {
        return {};
      }
    },
    // 外部查询结果集
    queryDataArr: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  components: { groupChoose },
  data() {
    return {
      loadingQuery: false, // 加载开关
      dataInit: [], // 绘图渲染使用的数据
      searchChoose: "", // 可选列查询关键字
      resAll: [], // 存储接受的请求数据
      size: "small",
      echartType: "line", // 绘图类型
      unitArr: [
        {
          label: "按天",
          value: "day"
        },
        {
          label: "按时",
          value: "hour"
        }
      ], // 时间跨度可选值
      unit: null, // 查询时间跨度
      dateS: [], // 开始时间段
      dateD: [], // 对比时间段
      messures: [], // 指标
      messuresCopy: [], // 映射指标数组
      messuresCopyInit: [], // 饼状图绘制用的 dom 存储数组
      pieBool: 0, // 饼图刷新开关
      byFields: [], // 分组
      myChart: null,
      chooseChecked: false, // 右侧全选
      rightChooseArr: [], // 右侧可选数组
      rightChooseArrShow: [], // 右侧关键字查询后的数组
      rightChooseArrInit: [], // 选中用来渲染的数组
      loop: 10
    };
  },
  watch: {
    // 右侧筛选条件监听
    rightChooseArrInit: {
      handler() {
        this.dataGeneration(); // 执行图表数据生成函数
        if (this.echartType == "line" || this.echartType == "bar") {
          this.echartInit(); // 执行图标生成渲染函数
        }
        if (this.echartType == "pie") {
          this.echartInitPie();
        }
      },
      deep: true
    },
    echartType: {
      handler() {
        this.chooseChecked = true;
        this.newChooseArr(); //  更新右侧点选列表
      },
      deep: true
    },
    loop: {
      handler() {
        this.searchChoose = "";
        this.chooseChecked = true;
        this.newChooseArr(); //  更新右侧点选列表
      },
      deep: true
    },
    queryTotal: {
      handler() {
        this.loadingQuery = true;
      },
      deep: true
    },
    // 观察指标选中数组   为饼图变量存储 dom  节点
    messuresCopy: {
      handler(newValue) {
        let arr = [];
        newValue.map(_i => {
          let obj = JSON.parse(JSON.stringify(_i));
          obj.myChart = null;
          arr.push(obj);
        });
        this.messuresCopyInit = arr;
        this.pieBool++;
        setTimeout(() => {
          if (this.echartType == "pie") {
            this.echartInitPie();
          }
        }, 100);
      },
      deep: true
    },
    queryDataArr: {
      handler() {
        this.queryDataHandle();
      },
      deep: true
    }
  },
  methods: {
    // 数据查询函数
    async queryDataHandle() {
      this.loadingQuery = false;
      if (!this.queryDataArr || this.queryDataArr.length < 1) {
        return;
      }

      let arr = JSON.parse(JSON.stringify(this.queryTotal.messures));
      this.messures = JSON.parse(JSON.stringify(arr));
      this.messuresCopy = JSON.parse(JSON.stringify(arr));
      let byFieldsArr = JSON.parse(JSON.stringify(this.queryTotal.byFields));
      byFieldsArr.map(_i => {
        _i.options = [];
        _i.checked = [];
      });
      this.byFields = byFieldsArr;

      this.resAll = this.queryDataArr;
      // 根据查询的结果，补充分组可选值
      let arrGroup = this.getArrGroup(this.queryTotal, this.queryDataArr);
      if (this.byFields.length == arrGroup.length) {
        let _arr = JSON.parse(JSON.stringify(this.byFields));
        _arr.map(_i => {
          arrGroup.map(_is => {
            if (_i.propertyId == _is.propertyId) {
              _i.options = _is.options;
              _i.checked = _is.options;
            }
          });
        });
        this.byFields = JSON.parse(JSON.stringify(_arr));
      }
      // 当有分组属性时，生成右侧可选列表
      this.newChooseArr();
    },
    // 生成右侧可选值列表
    newChooseArr() {
      let arr = [];
      if (this.queryTotal.byFields.length > 0) {
        this.resAll.map(_i => {
          _i.detailResult.rows.map((_is, _ins) => {
            if (!this.loop || this.loop > _ins) {
              let bool = true;
              _is.byValues.map((item, index) => {
                let boolL = false;
                this.byFields[index].checked.map(itemC => {
                  if (itemC == item) {
                    boolL = true;
                  }
                });
                if (!boolL) {
                  bool = false;
                }
              });
              if (bool) {
                arr.push(_is.byValues.join(" "));
              }
            }
          });
        });
      }
      arr = Array.from(new Set(arr));
      arr = arr.filter(_i => {
        return _i.indexOf(this.searchChoose) !== -1;
      });
      let _arr = [];

      this.messuresCopy.map(_i => {
        let obj = JSON.parse(JSON.stringify(_i));
        obj.showBool = true;
        obj.childrenChoose = JSON.parse(JSON.stringify(arr));
        obj.childrenChecked = JSON.parse(JSON.stringify(arr));
        _arr.push(obj);
      });
      this.rightChooseArr = JSON.parse(JSON.stringify(_arr));
      this.rightChooseArrShow = JSON.parse(JSON.stringify(_arr));
      this.rightChooseArrInit = JSON.parse(JSON.stringify(_arr));
    },
    groupChange(arr, index) {
      this.byFields[index].checked = JSON.parse(JSON.stringify(arr));
      this.newChooseArr();
    },
    rowLength() {
      let len = "0";
      try {
        len = this.resAll[0].detailResult.rows.length;
      } catch (err) {
        console.log(err, "长度计算失误");
      }
      return "当前共" + len + "项";
    },
    // 右侧显示折叠
    showBoolChange(bool, index) {
      let obj = JSON.parse(JSON.stringify(this.rightChooseArrShow[index]));
      obj.showBool = !bool;
      this.rightChooseArrShow.splice(index, 1, obj);
    },
    // 图标数据生成函数
    dataGeneration() {
      this.dataInit = [];
      this.resAll.map((item, index) => {
        this.dataInit.push([]);
        // 出参行数嵌套
        item.detailResult.rows.map((itemRow, indexRow) => {
          if (!this.loop || this.loop > indexRow) {
            // 指标嵌套
            this.queryTotal.messures.map((itemMess, indexMess) => {
              let line = {}; // 每条线的数据
              let bool = false; // 判断是否生成该行数据
              let name = itemRow.byValues.join(" ");
              // 根据筛选数据，判断 是否加入该行数据
              this.rightChooseArrInit.map(itemCI => {
                if (itemCI.echartId == itemMess.echartId && itemCI.name == itemMess.name) {
                  itemCI.childrenChecked.map(str => {
                    if (name == str) {
                      bool = true;
                    }
                  });
                }
              });
              if (
                bool ||
                !this.queryTotal.byFields ||
                this.queryTotal.byFields.length == 0
              ) {
                line.name = itemMess.name + " : " + name;
                line.data = [];
                itemRow.values.map(_itime => {
                  let keyTime = null;
                  if (index == 0) {
                    keyTime = "0";
                  } else {
                    keyTime = "1";
                  }
                  line.data.push({
                    value: _itime[indexMess],
                    keyTime: keyTime,
                    name: itemMess.name + " : " + name
                  });
                });
                this.dataInit[index].push(line);
              }
            });
          }
        });
      });
    },
    // 时间戳转日期
    zeroDel(time) {
      let date = new Date(time);
      let year = date.getFullYear();
      let mon = date.getMonth() + 1;
      let day = date.getDate();
      mon = mon < 10 ? "0" + mon : mon;
      day = day < 10 ? "0" + day : day;
      return year + "-" + mon + "-" + day;
    },
    // 饼状图绘制
    echartInitPie() {
      this.messuresCopyInit.map(_i => {
        try {
          if (!_i.myChart) {
            _i.myChart = this.$echarts.init(
              document.getElementById(_i.id + "pie"),
              "light"
            );
          }

          let itemArr = [];
          let tilArr = [];
          // 判断是否具有对比时间
          this.dataInit.map((itemTime, indexTime) => {
            let len = this.resAll[indexTime].detailResult.series.length;
            let name =
              this.zeroDel(this.resAll[indexTime].detailResult.series[0]) +
              " 至 " +
              this.zeroDel(this.resAll[indexTime].detailResult.series[len - 1]);

            let data = [];
            itemTime.map(itemLine => {
              if (itemLine.name.indexOf(_i.name) !== -1) {
                let total = 0;
                itemLine.data.map(_is => {
                  total += _is.value;
                });
                data.push({
                  name: itemLine.name,
                  value: total
                });
              }
            });
            let left = "";
            let leftTil = "50%";
            if (this.dataInit.length == 2 && indexTime == 1) {
              left = "54%";
              leftTil = "76%";
            }
            if (this.dataInit.length == 2 && indexTime == 0) {
              left = "-54%";
              leftTil = "23%";
            }
            tilArr.push({
              text: name,
              left: leftTil,
              top: "90%",
              textAlign: "center",
              textStyle: {
                fontWeight: "normal",
                fontSize: "16",
                color: "#AAAFC8",
                textAlign: "center"
              }
            });
            itemArr.push({
              type: "pie",
              left: left,
              radius: ["40%", "70%"],
              avoidLabelOverlap: true,
              itemStyle: {
                borderRadius: 10,
                borderColor: "#fff",
                borderWidth: 2
              },
              label: {
                show: false
              },
              data: data
            });
          });
          _i.myChart.clear();
          let option = {
            // title: {
            //   subtext: _i.name,
            //   left: "center"
            // },
            title: tilArr,
            tooltip: {
              trigger: "item"
            },
            series: itemArr
          };
          _i.myChart.setOption(option, true);
          setTimeout(() => {
            _i.myChart.resize();
          }, 10);
        } catch (err) {
          console.log("pie图绘制错误", err);
        }
      });
    },
    // 折线图 柱状图绘制
    echartInit() {
      let byFieldsBool = true; // 判断是否具有分组参数
      if (
        !this.resAll[0].detailResult.byFields ||
        this.resAll[0].detailResult.byFields.length == 0
      ) {
        byFieldsBool = false;
      }
      let _arr = []; // 画图渲染数据
      let xAxisArr = []; // 底部时间轴
      let formatter; // 提示函数
      let currentSeriesIndex = 0; // 保存鼠标移入是，当前指向
      this.resAll.map(_i => {
        _i.detailResult.series.map((_is, _ins) => {
          let date = new Date(_is);
          let year = date.getFullYear();
          let mon = date.getMonth() + 1;
          mon = mon < 10 ? "0" + mon : mon;
          let day = date.getDate();
          day = day < 10 ? "0" + day : day;
          let str = year + "-" + mon + "-" + day;
          if (xAxisArr[_ins]) {
            xAxisArr[_ins] += " 与 ";
            xAxisArr[_ins] += str;
          } else {
            xAxisArr.push(str);
          }
        });
      });
      this.myChart.on("mouseover", param => {
        currentSeriesIndex = param.seriesIndex;
      });

      // 折线图
      if (this.echartType == "line") {
        // 生成渲染数据  有分组
        this.dataInit.map(_i => {
          _i.map(_is => {
            _arr.push({
              name: _is.name,
              data: JSON.parse(JSON.stringify(_is.data)),
              type: this.echartType
            });
          });
        });
        // 生成渲染数据 无分组
        if (!byFieldsBool) {
          _arr = [];
          this.resAll.map((item, index) => {
            this.messuresCopy.map(itemMess => {
              let obj = {};
              obj.name = itemMess.name;
              obj.type = this.echartType;
              obj.data = [];
              item.totalDetailResult.series.map((itemTime, indexTime) => {
                this.queryTotal.messures.map((itemCopy, indexCopy) => {
                  if (itemCopy.echartId == itemMess.echartId && itemCopy.name == itemMess.name) {
                    obj.data.push({
                      value:
                        item.totalDetailResult.rows[0].values[indexTime][
                          indexCopy
                        ],
                      keyTime: index,
                      name: itemMess.name
                    });
                  }
                });
              });
              _arr.push(obj);
            });
          });
        }
        // 生成提示函数
        formatter = params => {
          // 获取时间提示文字 及顶部提示文字
          let axisValueArr = params[0].axisValue.split(" 与 ");
          let resHtml = "";
          if (axisValueArr.length > 1) {
            resHtml += `
              <div class="tooltipContent">
                <div class="name">指标及分组值</div>
                <div class="value">${axisValueArr[0]}</div>
                <div class="value">${axisValueArr[1]}</div>
              </div>
              `;
          } else {
            resHtml += `
              <div class="tooltipContent">
                <div class="name">指标及分组值</div>
                <div class="value">${axisValueArr[0]}</div>
                <div class="value"></div>
              </div>
              `;
          }
          // 根据选中的筛选条件，进行提示文字的渲染
          let arr = [];
          if (byFieldsBool) {
            this.rightChooseArrInit.map(_i => {
              let obj = {};
              obj.name = _i.name;
              obj.checked = [];
              _i.childrenChecked.map(_is => {
                let _o = {};
                _o.name = _is;
                _o.oneTime = "";
                _o.color = null;
                _o.twoTime = "";
                params.map(param => {
                  let { color } = param;
                  if (
                    param.seriesName.indexOf(_is) !== -1 &&
                    param.seriesName.indexOf(_i.name) !== -1 &&
                    param.data.keyTime == "0"
                  ) {
                    _o.oneTime = param.data.value;
                    _o.color = color;
                  }
                  if (
                    param.seriesName.indexOf(_is) !== -1 &&
                    param.seriesName.indexOf(_i.name) !== -1 &&
                    param.data.keyTime == "1"
                  ) {
                    _o.twoTime = param.data.value;
                    _o.color = color;
                  }
                });
                obj.checked.push(_o);
              });
              arr.push(obj);
            });
            arr.map(_i => {
              if (_i.checked.length > 0) {
                resHtml += `
                  <div class="tooltipContent">
                    <div class="head">${_i.name}</div>
                  </div>
                `;
                _i.checked.map(_is => {
                  resHtml += `
                  <div class="tooltipContent">
                    <div class="name">
                       <span class="name-index" style="background-color:${_is.color}"></span>
                      ${_is.name}
                    </div>
                    <div class="value">${_is.oneTime}</div>
                    <div class="value">${_is.twoTime}</div>
                  </div>
                  `;
                });
                resHtml += `</div>`;
              }
            });
          } else {
            this.messuresCopy.map(item => {
              let obj = {};
              obj.name = item.name;
              obj.oneTime = "";
              obj.twoTime = "";
              obj.color = "";
              params.map(param => {
                if (item.name == param.name && param.data.keyTime == 0) {
                  obj.oneTime = param.data.value;
                  obj.color = param.color;
                }
                if (item.name == param.name && param.data.keyTime == 1) {
                  obj.twoTime = param.data.value;
                  obj.color = param.color;
                }
              });
              arr.push(obj);
            });
            arr.map(_i => {
              resHtml += `
                  <div class="tooltipContent">
                    <div class="name">
                       <span class="name-index" style="background-color: ${_i.color}"></span>
                      ${_i.name}
                    </div>
                    <div class="value">${_i.oneTime}</div>
                    <div class="value">${_i.twoTime}</div>
                  </div>
                  `;
            });
          }
          return resHtml;
        };
      }
      // 柱状图
      if (this.echartType == "bar") {
        // 生成渲染数据 有分组
        this.dataInit.map((itemTime, indexTime) => {
          itemTime.map(itemLine => {
            let obj = {
              name: itemLine.name.split(" : ")[1],
              // stack : itemLine.name,
              stack: itemLine.name.split(" : ")[0] + indexTime,
              type: this.echartType,
              // barWidth: '5%',
              data: itemLine.data
            };
            _arr.push(obj);
          });
        });
        // 生成渲染数据 无分组
        if (!byFieldsBool) {
          _arr = [];
          this.resAll.map((item, index) => {
            this.messuresCopy.map(itemMess => {
              let obj = {};
              obj.name = itemMess.name;
              obj.stack = itemMess.name + index;
              obj.type = this.echartType;
              obj.data = [];
              item.totalDetailResult.series.map((itemTime, indexTime) => {
                this.queryTotal.messures.map((itemCopy, indexCopy) => {
                  if (itemCopy.echartId == itemMess.echartId && itemCopy.name == itemMess.name) {
                    obj.data.push({
                      keyTime: index,
                      name: itemMess.name,
                      value:
                        item.totalDetailResult.rows[0].values[indexTime][
                          indexCopy
                        ]
                    });
                  }
                });
              });
              _arr.push(obj);
            });
          });
        }
        // 生成提示函数
        formatter = params => {
          // 获取时间提示文字 及顶部提示文字
          let axisValueArr = params[0].axisValue.split(" 与 ");
          let resHtml = "";
          let tilOne = axisValueArr[0] ? axisValueArr[0] : "";
          let tilTwo = axisValueArr[1] ? axisValueArr[1] : "";
          resHtml += `
              <div class="tooltipContent">
                <div class="name">指标及分组值</div>
                <div class="value">${tilOne}</div>
                <div class="value">${tilTwo}</div>
              </div>
              `;
          let name = params[currentSeriesIndex].name;
          let color = params[currentSeriesIndex].color;
          let oneValue = "";
          let twoValue = "";
          if (byFieldsBool) {
            let timeIndex = null; // 时间下标l
            params.map((param, index) => {
              if (index == currentSeriesIndex && param.data.keyTime == "1") {
                name = param.data.name;
                twoValue = param.data.value;
                color = param.color;
                xAxisArr.map((_i, _in) => {
                  if (_i == param.axisValue) {
                    timeIndex = _in;
                  }
                });
              }
              if (index == currentSeriesIndex && param.data.keyTime == "0") {
                name = param.data.name;
                oneValue = param.data.value;
                color = param.color;
                xAxisArr.map((_i, _in) => {
                  if (_i == param.axisValue) {
                    timeIndex = _in;
                  }
                });
              }
            });
            if (!oneValue && this.dataInit[0]) {
              this.dataInit[0].map(_i => {
                if (_i.name == name && !oneValue) {
                  oneValue = _i.data[timeIndex].value;
                }
              });
            }

            if (!twoValue && this.dataInit[1]) {
              this.dataInit[1].map(_i => {
                if (_i.name == name && !twoValue) {
                  twoValue = _i.data[timeIndex].value;
                }
              });
            }
          } else {
            params.map(param => {
              if (param.name == name && param.data.keyTime == 0) {
                oneValue = param.data.value;
              }
              if (param.name == name && param.data.keyTime == 1) {
                twoValue = param.data.value;
              }
            });
          }
          resHtml += `
                  <div class="tooltipContent">
                    <div class="name">
                       <span class="name-index" style="background-color: ${color}"></span>
                      ${name}
                    </div>
                    <div class="value">${oneValue}</div>
                    <div class="value">${twoValue}</div>
                  </div>
                  `;
          return resHtml;
        };
      }
      let option = {
        backgroundColor: "#fff",
        grid: {
          left: "10%",
          top: "10%",
          right: "10%"
        },
        tooltip: {
          trigger: "axis",
          backgroundColor: "#001529",
          textStyle: {
            color: "#fff"
          },
          padding: [10, 10],
          extraCssText: "box-shadow: 1px 0 2px 0 rgba(163,163,163,0.5)",
          formatter: formatter
        },
        xAxis: {
          type: "category",
          boundaryGap: this.echartType === "line" ? false : true,
          data: xAxisArr
        },
        yAxis: {
          type: "value"
        },
        series: _arr
      };
      this.myChart.setOption(option, true);
      ElementResize.on(document.getElementById("echCanvas"), () => {
          try {
            this.myChart.resize();
          } catch (err) {
            console.log(err);
          }
        });
      // 清除之前画布
      try{
         setTimeout(() => {
            this.myChart.resize();
         }, 200);
      }catch(err){
        console.log('缩放失败',err)
      }
    },
    // 全选点击
    allChoose(v) {
      if (v) {
        this.newChooseArr();
      } else {
        this.rightChooseArrInit.map(_i => {
          _i.childrenChecked = [];
        });
      }
    },
    // 渲染条件更改  参数三用来判断 是否进行全部替换
    rightChooseArrInitChange(item, indexOne, totalBool) {
      let index;
      let obj = JSON.parse(JSON.stringify(this.rightChooseArrInit[indexOne]));
      let bool = false;
      let _arr = [];
      obj.childrenChecked.map((_i, _in) => {
        if (_i == item) {
          bool = true;
          index = _in;
        }
      });

      if (bool) {
        obj.childrenChecked.splice(index, 1);
      } else {
        obj.childrenChecked.push(item);
      }
      _arr = JSON.parse(JSON.stringify(obj.childrenChecked));
      if (totalBool) {
        let arr = JSON.parse(JSON.stringify(this.rightChooseArrInit));
        arr.map(_i => {
          _i.childrenChecked = JSON.parse(JSON.stringify(_arr));
        });
        this.rightChooseArrInit = arr;
      } else {
        this.rightChooseArrInit.splice(indexOne, 1, obj);
      }
    },
    opacityShow(v, index) {
      let bool = false;
      this.rightChooseArrInit[index].childrenChecked.map(_i => {
        if (_i == v) {
          bool = true;
        }
      });
      return bool;
    },
    // 获取分组可选值函数
    getArrGroup(enter, out) {
      let _arr = JSON.parse(JSON.stringify(enter.byFields));
      _arr.map(_i => {
        _i.options = [];
      });
      if (!enter.byFields || enter.byFields.length == 0) {
        return _arr;
      }
      out.map(item => {
        item.detailResult.rows.map(itemRow => {
          itemRow.byValues.map((itemByv, indexByv) => {
            _arr[indexByv].options.push(itemByv);
          });
        });
      });
      _arr.map(item => {
        item.options = Array.from(new Set(item.options));
      });
      return _arr;
    },
    // 指标显示
    messuresShow(item) {
      let str = "cancle_arr ";
      this.messuresCopy.map(_i => {
        if (_i.echartId == item.echartId && _i.name == item.name) {
          str += "index_arr";
        }
      });
      return str;
    },
    // 显示指标更改函数
    messuresCopyChange(item) {
      let bool = false;
      let index = 0;
      this.messuresCopy.map((_i, _in) => {
        if (_i.echartId == item.echartId && _i.name == item.name) {
          bool = true;
          index = _in;
        }
      });
      if (bool) {
        this.messuresCopy.splice(index, 1);
      } else {
        this.messuresCopy.push(JSON.parse(JSON.stringify(item)));
      }
      this.newChooseArr();
    },
    //  追加对比 时间函数
    timeContrast(v) {
      let arr = [0, 0];
      // 同段时间
      if (v == "1") {
        let c = new Date(this.dateS[1]) - new Date(this.dateS[0]);
        arr[1] = new Date(this.dateS[0]) - 24 * 60 * 60 * 1000;
        arr[0] = arr[1] - c;
      }
      // 自定义时间
      if (v == "2") {
        arr[0] = new Date(this.dateS[0]) - 24 * 60 * 60 * 1000;
        arr[1] = new Date(this.dateS[1]) - 24 * 60 * 60 * 1000;
      }
      this.dateD = arr;
    },
    convert(num) {
      return num <= 26
        ? String.fromCharCode(num + 64)
        : this.convert(~~((num - 1) / 26)) + this.convert(num % 26 || 26);
    },
    dateSChange(newValue) {
      let startDate = null;
      let endDate = null;
      let contrastStartDate = null;
      let contrastEndDate = null;
      if (newValue && newValue[0]) {
        let date = new Date(newValue[0]);
        let year = date.getFullYear();
        let mon = date.getMonth() + 1;
        let day = date.getDate();
        startDate = year + "-" + mon + "-" + day;
      }
      if (newValue && newValue[1]) {
        let date = new Date(newValue[1]);
        let year = date.getFullYear();
        let mon = date.getMonth() + 1;
        let day = date.getDate();
        endDate = year + "-" + mon + "-" + day;
      }
      if (this.dateD && this.dateD[0]) {
        let date = new Date(this.dateD[0]);
        let year = date.getFullYear();
        let mon = date.getMonth() + 1;
        let day = date.getDate();
        contrastStartDate = year + "-" + mon + "-" + day;
      }
      if (this.dateD && this.dateD[1]) {
        let date = new Date(this.dateD[1]);
        let year = date.getFullYear();
        let mon = date.getMonth() + 1;
        let day = date.getDate();
        contrastEndDate = year + "-" + mon + "-" + day;
      }
      this.$emit("conversion", {
        unit: this.unit,
        startDate,
        endDate,
        contrastStartDate,
        contrastEndDate
      });
    },
    dateDChange(newValue) {
      let startDate = null;
      let endDate = null;
      let contrastStartDate = null;
      let contrastEndDate = null;
      if (this.dateS && this.dateS[0]) {
        let date = new Date(this.dateS[0]);
        let year = date.getFullYear();
        let mon = date.getMonth() + 1;
        let day = date.getDate();
        startDate = year + "-" + mon + "-" + day;
      }
      if (this.dateS && this.dateS[1]) {
        let date = new Date(this.dateS[1]);
        let year = date.getFullYear();
        let mon = date.getMonth() + 1;
        let day = date.getDate();
        endDate = year + "-" + mon + "-" + day;
      }
      if (newValue && newValue[0]) {
        let date = new Date(newValue[0]);
        let year = date.getFullYear();
        let mon = date.getMonth() + 1;
        let day = date.getDate();
        contrastStartDate = year + "-" + mon + "-" + day;
      }
      if (newValue && newValue[1]) {
        let date = new Date(newValue[1]);
        let year = date.getFullYear();
        let mon = date.getMonth() + 1;
        let day = date.getDate();
        contrastEndDate = year + "-" + mon + "-" + day;
      }
      this.$emit("conversion", {
        unit: this.unit,
        startDate,
        endDate,
        contrastStartDate,
        contrastEndDate
      });
      this.searchChoose = "";
    },
    unitChange(newValue) {
      let startDate = null;
      let endDate = null;
      let contrastStartDate = null;
      let contrastEndDate = null;
      if (this.dateS && this.dateS[0]) {
        let date = new Date(this.dateS[0]);
        let year = date.getFullYear();
        let mon = date.getMonth() + 1;
        let day = date.getDate();
        startDate = year + "-" + mon + "-" + day;
      }
      if (this.dateS && this.dateS[1]) {
        let date = new Date(this.dateS[1]);
        let year = date.getFullYear();
        let mon = date.getMonth() + 1;
        let day = date.getDate();
        endDate = year + "-" + mon + "-" + day;
      }
      if (this.dateD && this.dateD[0]) {
        let date = new Date(this.dateD[0]);
        let year = date.getFullYear();
        let mon = date.getMonth() + 1;
        let day = date.getDate();
        contrastStartDate = year + "-" + mon + "-" + day;
      }
      if (this.dateD && this.dateD[1]) {
        let date = new Date(this.dateD[1]);
        let year = date.getFullYear();
        let mon = date.getMonth() + 1;
        let day = date.getDate();
        contrastEndDate = year + "-" + mon + "-" + day;
      }
      this.$emit("conversion", {
        unit: newValue,
        startDate,
        endDate,
        contrastStartDate,
        contrastEndDate
      });
    }
  },
  beforeCreate() {},
  created() {
    this.unit = this.queryTotal.searchTime.unit; // 处理接受 时间跨度
    // 模拟入参数据
    let _arr = [
      this.queryTotal.searchTime.startDate,
      this.queryTotal.searchTime.endDate
    ];
    if (!_arr[0] || !_arr[1]) {
      _arr[0] = _arr[1] = new Date().valueOf();
    }
    let _arrD = [
      this.queryTotal.searchTime.contrastStartDate,
      this.queryTotal.searchTime.contrastEndDate
    ];
    if (!_arrD[0] || !_arrD[1]) {
      _arrD = null;
    }
    this.dateS = _arr; // 处理接受 开始时间
    this.dateD = _arrD; // 处理接受 对比时间段
  },
  beforeMount() {},
  mounted() {
    this.myChart = this.$echarts.init(
      document.getElementById("echCanvas"),
      "light"
    );
  },
  computed: {}
};
</script>
<style lang="scss">
.tooltipContent {
  display: flex;
  .head {
    height: 36px;
    font-weight: 500;
    letter-spacing: 4px;
    text-indent: 8px;
    line-height: 36px;
    color: rgba($color: #c0c4cc, $alpha: 1);
  }
  .name {
    flex-grow: 1;
    margin-right: 10px;
    font-size: 10px;
    align-items: center;
    display: flex;
    .name-index {
      margin-right: 5px;
      width: 10px;
      height: 10px;
      display: inline-block;
      line-height: 20px;
      text-align: center;
      -webkit-border-radius: 50%;
      -moz-border-radius: 50%;
      border-radius: 50%;
    }
  }
  .value {
    font-size: 10px;
    width: 100px;
    text-align: center;
  }
}
</style>
<style scoped lang="scss">
* {
  box-sizing: border-box;
}
::v-deep .show_hidden {
  visibility: hidden;
  position: absolute;
  left: 0;
  top: -0.2rem;
  z-index: 10;
}
::v-deep .el-input--suffix {
  height: 0.5rem;
  overflow: hidden;
}

.event_echart {
  margin: 0.24rem auto;
  padding-bottom: 0.2rem;
  .ech_show {
    width: 99%;
    margin: 0.1rem auto;
    height: 8rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    #echCanvas,
    .pieCanvas {
      height: 99%;
      // flex: 1;
      // width: calc(100% - 4.6rem);
      flex: 1;
      .pieContBig,
      .pieContSmall {
        display: inline-block;
        height: 6rem;
        .head {
          width: 100%;
          height: 1.2rem;
          display: flex;
          align-items: center;
          justify-content: center;
          color: rgba($color: #303133, $alpha: 1);
          font-size: 0.22rem;
          letter-spacing: 2px;
        }
        .canvas {
          width: 100%;
          height: 4.8rem;
        }
      }
      .pieContBig {
        width: 100%;
      }
      .pieContSmall {
        width: 50%;
      }
    }
    .pieCanvas {
      overflow-y: scroll;
    }
    .pieCanvas::-webkit-scrollbar {
      display: none;
    }
    .echChoose {
      height: 99%;
      width: 4.6rem;
      max-width: 360px;
      min-width: 200px;
      // border-left: 1px solid rgba($color: #01b27a, $alpha: 0.3);
      .choose {
        width: 100%;
        height: 0.6rem;
        display: flex;
        align-items: center;
        padding-left: 0.2rem;
      }
      .scrool::-webkit-scrollbar {
        display: none;
      }
      .scrool {
        height: calc(100% - 0.6rem);
        overflow-y: scroll;

        .boxfather {
          cursor: pointer;
          .head {
            width: 100%;
            margin: 0 auto;
            height: 0.4rem;
            display: flex;
            align-items: center;
            justify-content: flex-start;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-weight: 500;
            letter-spacing: 2px;
            i {
              font-size: 16px;
              margin: 0 0.2rem;
              color: rgb(119, 140, 162);
            }
          }

          .cont {
            width: 100%;
            margin: 0 auto;
            .line {
              display: flex;
              opacity: 0.3;
              align-items: center;
              justify-content: flex-start;
              text-indent: 0.8rem;
              color: #475669;
              width: 100%;
              height: 0.4rem;
              letter-spacing: 1px;
              cursor: pointer;
              text-overflow: ellipsis;
              overflow: hidden;
              white-space: nowrap;
            }
            .line:hover {
              color: rgba($color: #01b27a, $alpha: 0.9);
            }
            .active {
              opacity: 1 !important;
            }
          }
        }
      }
    }
  }
  .config_arr {
    width: 100%;
    margin: 0.1rem auto;
    min-height: 0.6rem;
    border-bottom: 1px solid #e4e7ed;
    .left {
      width: 60%;
      display: flex;
      align-items: center;
      .min_el {
        width: 2rem;
        display: flex;
        align-items: center;
        margin-right: 0.3rem;
      }
    }
    .right {
      width: 40%;
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }
    .cancle_arr {
      height: 0.6rem;
      cursor: pointer;
      width: 3.8rem;
      margin-right: 0.2rem;
      line-height: 0.5rem;
      font-size: 12px;
      opacity: 0.3;
      .icon {
        display: inline-block;
        text-align: center;
        line-height: 0.3rem;
        width: 0.3rem;
        cursor: pointer;
        height: 0.3rem;
        background: #c0c4cc;
        border-radius: 50%;
        color: #606266;
        margin: 0 0.1rem;
      }
      .no_icon {
        display: inline-block;
        text-align: center;
        line-height: 0.3rem;
        width: 0.3rem;
        cursor: pointer;
        height: 0.3rem;
        border-radius: 50%;
        color: white;
        margin: 0 0.1rem;
        background: #909399;
      }
    }
    .index_arr {
      opacity: 1;
      .icon {
        background: #00bf8a;
        color: white;
      }
    }
  }
  .no_line {
    border-bottom: none;
    .group_sun {
      min-width: 1.8rem;
      padding: 0 0.2rem;
      min-height: 0.4rem;
      margin: 0.1rem 0.2rem 0.1rem 0;
      line-height: 0.4rem;
      border: 1px solid #c0c4cc;
      font-size: 10px;
      border-radius: 4px;
      display: inline-block;
      text-align: center;
      position: relative;
      .checklength {
        display: inline-block;
        width: 0.46rem;
        height: 0.3rem;
        line-height: 0.3rem;
        text-align: center;
        margin-left: 0.2rem;
        border-radius: 3px;
        font-size: 0.16rem;
        font-weight: 400;
        background: rgba($color: #e4e7ed, $alpha: 0.9);
      }
    }
    .group_sun:hover {
      color: rgba($color: #01b27a, $alpha: 0.8);
      border-color: rgba($color: #01b27a, $alpha: 0.8);
    }
  }
  .btwn {
    min-height: 0.8rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .sel_inp {
      width: 5rem;
      transform: scale(0.9, 0.8);
      margin-left: 0;
    }
    .time {
      width: 4rem;
      margin: 0 0.1rem;
    }
    .total_screen {
      cursor: pointer;
      position: relative;
      margin: 0 0 0 0.2rem;
      color: #307ef2;
      i {
        font-weight: 800;
      }
    }
    .right {
      span {
        width: 0.4rem;
        height: 0.4rem;
        display: inline-block;
        text-align: center;
        line-height: 0.4rem;
        margin: 0 0.1rem;
        border-radius: 2px;
      }
      .active {
        background: rgba($color: #01b27a, $alpha: 0.6);
        color: rgba($color: white, $alpha: 0.8);
        font-weight: 800;
      }
    }
  }
}
</style>
